﻿/*
Copyright (c) 2008 Ryan BB Schreiber, Brendan G Fry

Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal in 
the Software without restriction, including without limitation the rights to 
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
of the Software, and to permit persons to whom the Software is furnished to do 
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Castle.ActiveRecord;
using log4net;
using NHibernate;
using NHibernate.Criterion;

namespace Darkside.GeneratorStudio.Library.Domain
{
    public partial class Column
    {
        private static readonly ILog _Log = LogManager.GetLogger(typeof(Column));
        public bool IsNullable { get { return m_IsNullable == "YES"; } }

        public static IList<Column> FindAllByTable (Table table)
        {
            return FindAll(new ICriterion[] {Restrictions.Eq("TableName", table.Name)});
        }

        public bool IsPrimaryKey { get; set; }
        public bool IsCompositePrimaryKeyMember { get; set; }

        public bool IsForeignKey { get; set; }
        //public bool IsCompositeForeignKeyMember { get; set; }

        private bool? _IsIdentity;
        public bool IsIdentity
        {
            get
            {
                if (!_IsIdentity.HasValue)
                {
                    _IsIdentity = GetIsIdentity();
                }
                return _IsIdentity.Value;
            }
        }

        public string SqlTypeString
        {
            get
            {
                if ((DataType.Equals("bigint"))
                    || (DataType.Equals("int"))
                    || (DataType.Equals("smallint"))
                    || (DataType.Equals("tinyint"))
                    || (DataType.Equals("bit"))
                    || (DataType.Equals("datetime"))
                    || (DataType.Equals("smalldatetime"))
                    || (DataType.Equals("money"))
                    || (DataType.Equals("smallmoney"))
                    || (DataType.Equals("float"))
                    || (DataType.Equals("real"))
                    || (DataType.Equals("ntext"))
                    || (DataType.Equals("text"))
                    || (DataType.Equals("image"))
                    || (DataType.Equals("uniqueidentifier"))
                    || (DataType.Equals("timestamp"))
                    || (DataType.Equals("xml"))
                    )
                    return DataType;

                if ((DataType.Equals("char"))
                    || (DataType.Equals("varchar"))
                    || (DataType.Equals("nchar"))
                    || (DataType.Equals("nvarchar"))
                    || (DataType.Equals("binary"))
                    || (DataType.Equals("varbinary"))
                    )
                    return String.Format("{0}({1})", DataType, CharacterMaximumLength);

                if ((DataType.Equals("decimal"))
                    || (DataType.Equals("numeric"))
                    )
                    return String.Format("{0}({1},{2})", DataType, NumericScale, NumericPrecision);

                throw new Exception("Unexpected data type: " + DataType);
            }
        }

        public string NetTypeString
        {
            get
            {
                string sqlType = DataType;
                // the suffix will add "?" at end if .net type is not a class and field is nullable
                string suffix = (IsNullable) ? "?" : "";

                if (sqlType.Equals("bigint")) return "long" + suffix;
                if (sqlType.Equals("int")) return "int" + suffix;
                if (sqlType.Equals("smallint")) return "short" + suffix;
                if (sqlType.Equals("tinyint")) return "byte" + suffix;
                if (sqlType.Equals("bit")) return "bool" + suffix;
                if (sqlType.Equals("decimal")) return "System.Decimal" + suffix;
                if (sqlType.Equals("numeric")) return "System.Decimal" + suffix;
                if (sqlType.Equals("money")) return "System.Decimal" + suffix;
                if (sqlType.Equals("smallmoney")) return "System.Decimal" + suffix;
                if (sqlType.Equals("float")) return "float" + suffix;
                if (sqlType.Equals("real")) return "double" + suffix;
                if (sqlType.Equals("datetime")) return "DateTime" + suffix;
                if (sqlType.Equals("smalldatetime")) return "DateTime" + suffix;
                if (sqlType.Equals("varchar")) return "string";
                if (sqlType.Equals("nchar")) return "string";
                if (sqlType.Equals("char")) return "string";
                if (sqlType.Equals("text")) return "string"; // might be HUGE!
                if (sqlType.Equals("nvarchar")) return "string";
                if (sqlType.Equals("ntext")) return "string";
                if (sqlType.Equals("binary")) return "byte[]";
                if (sqlType.Equals("varbinary")) return "byte[]";
                if (sqlType.Equals("image")) return "byte[]";
                if (sqlType.Equals("timestamp")) return "long" + suffix;
                if (sqlType.Equals("uniqueidentifier")) return "Guid" + suffix; // this MAY be a byte[16] array
                if (sqlType.Equals("xml")) return "string";
                throw new Exception("Unexpected data type: " + DataType);
            }
        }

        public string NHibernateTypeString
        {
            get
            {
                string sqlType = DataType;

                if (CharacterMaximumLength == 1)
                {
                    if (sqlType.Equals("char")) return "AnsiChar";
                    if (sqlType.Equals("nchar")) return "AnsiChar";
                }

                if (sqlType.Equals("bigint")) return "Int64";
                if (sqlType.Equals("int")) return "Int32";
                if (sqlType.Equals("smallint")) return "Int16";
                if (sqlType.Equals("tinyint")) return "Byte";
                if (sqlType.Equals("bit")) return "Boolean";
                if (sqlType.Equals("decimal")) return "Decimal";
                if (sqlType.Equals("numeric")) return "Decimal";
                if (sqlType.Equals("money")) return "Decimal";
                if (sqlType.Equals("smallmoney")) return "Decimal";
                if (sqlType.Equals("float")) return "Double";
                if (sqlType.Equals("real")) return "Double";
                if (sqlType.Equals("datetime")) return "DateTime";
                if (sqlType.Equals("smalldatetime")) return "DateTime";
                if (sqlType.Equals("char")) return "string";
                if (sqlType.Equals("varchar")) return "String";
                if (sqlType.Equals("text")) return "String";
                if (sqlType.Equals("nchar")) return "string";
                if (sqlType.Equals("nvarchar")) return "String";
                if (sqlType.Equals("ntext")) return "String";
                if (sqlType.Equals("binary")) return "Binary";
                if (sqlType.Equals("varbinary")) return "Binary";
                if (sqlType.Equals("image")) return "Binary";
                if (sqlType.Equals("timestamp")) return "Int64";
                if (sqlType.Equals("uniqueidentifier")) return "Guid"; // this MAY be a byte[16] array
                if (sqlType.Equals("xml")) return "String";
                throw new Exception("Unexpected data type: " + DataType);
            }
        }

        public string InequalityTest
        {
            get
            {
                if (IsForeignKey)
                {
                    // test the IDs of the ActiveRecord objects
                    return "(" + Name + " == null) || (value == null))";
                        // " || (value." + ForeignKeyInfo.PKColumn + " != " + GetPrivateVariableName() + "." + ForeignKeyInfo.PKColumn + ")";
                }
                if ((NetTypeString.Equals("string")) || (NetTypeString.Equals("datetime")))
                {
                    // test object equality
                    return "(" + Name + " == null) || (value == null) || (!value.Equals(" + Name + "))";
                }
                return "value != " + Name;
            }
        }

        public string Description
        {
            get
            {
                ISession session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ActiveRecordBase));

                var connection = session.Connection;


                if (connection.State != ConnectionState.Open)
                    connection.Open();

                try
                {

                    IDbCommand command = connection.CreateCommand();
                    command.CommandText = @"SELECT VALUE FROM ::fn_listextendedproperty ('MS_Description','user','dbo','table',@table,'column',@column)";

                    command.CommandType = CommandType.Text;

                    IDbDataParameter parameter1 = command.CreateParameter();
                    parameter1.ParameterName = "@table";
                    parameter1.Value = TableName;
                    command.Parameters.Add(parameter1);
                    IDbDataParameter parameter2 = command.CreateParameter();
                    parameter2.ParameterName = "@column";
                    parameter2.Value = Name;
                    command.Parameters.Add(parameter2);

                    return Convert.ToString(command.ExecuteScalar());
                }
                catch (SqlException sqlEx)
                {
                    _Log.Error(sqlEx.Message, sqlEx);
                    throw;
                }
            }
        }

        private bool GetIsIdentity()
        {
            ISession session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ActiveRecordBase));

            var connection = session.Connection;


            if (connection.State != ConnectionState.Open)
                connection.Open();

            try
            {

                IDbCommand command = connection.CreateCommand();
                command.CommandText = @"SELECT COLUMNPROPERTY(object_id(@table), @column, 'IsIdentity')";

                command.CommandType = CommandType.Text;

                IDbDataParameter parameter1 = command.CreateParameter();
                parameter1.ParameterName = "@table";
                parameter1.Value = TableName;
                command.Parameters.Add(parameter1);
                IDbDataParameter parameter2 = command.CreateParameter();
                parameter2.ParameterName = "@column";
                parameter2.Value = Name;
                command.Parameters.Add(parameter2);


                int i = Convert.ToInt32(command.ExecuteScalar());
                return (i == 1);

            }
            catch (SqlException sqlEx)
            {
                _Log.Error(sqlEx.Message, sqlEx);
                throw;
            }
        }

        public bool IsNameReservedWord
        {
            get
            {
                return _reservedKeywords.Contains(Name, StringComparer.InvariantCultureIgnoreCase);
            }
        }

        private readonly string[] _reservedKeywords = new []
                                                {
                                                    "ADD", "EXISTS", "PRIMARY", "ALL", "EXIT", "PRINT", "ALTER",
                                                    "EXTERNAL", "PROC", "AND", "FETCH", "PROCEDURE", "ANY", "FILE",
                                                    "PUBLIC", "AS", "FILLFACTOR", "RAISERROR", "ASC", "FOR", "READ",
                                                    "AUTHORIZATION", "FOREIGN", "READTEXT", "BACKUP", "FREETEXT",
                                                    "RECONFIGURE", "BEGIN", "FREETEXTTABLE", "REFERENCES", "BETWEEN",
                                                    "FROM", "REPLICATION", "BREAK", "FULL", "RESTORE", "BROWSE",
                                                    "FUNCTION", "RESTRICT", "BULK", "GOTO", "RETURN", "BY", "GRANT",
                                                    "REVERT", "CASCADE", "GROUP", "REVOKE", "CASE", "HAVING", "RIGHT",
                                                    "CHECK", "HOLDLOCK", "ROLLBACK", "CHECKPOINT", "IDENTITY",
                                                    "ROWCOUNT", "CLOSE", "IDENTITY_INSERT", "ROWGUIDCOL", "CLUSTERED",
                                                    "IDENTITYCOL", "RULE", "COALESCE", "IF", "SAVE", "COLLATE", "IN",
                                                    "SCHEMA", "COLUMN", "INDEX", "SECURITYAUDIT", "COMMIT", "INNER",
                                                    "SELECT", "COMPUTE", "INSERT", "SESSION_USER", "CONSTRAINT",
                                                    "INTERSECT", "SET", "CONTAINS", "INTO", "SETUSER", "CONTAINSTABLE",
                                                    "IS", "SHUTDOWN", "CONTINUE", "JOIN", "SOME", "CONVERT", "KEY",
                                                    "STATISTICS", "CREATE", "KILL", "SYSTEM_USER", "CROSS", "LEFT",
                                                    "TABLE", "CURRENT", "LIKE", "TABLESAMPLE", "CURRENT_DATE", "LINENO",
                                                    "TEXTSIZE", "CURRENT_TIME", "LOAD", "THEN", "CURRENT_TIMESTAMP",
                                                    "NATIONAL", "TO", "CURRENT_USER", "NOCHECK", "TOP", "CURSOR",
                                                    "NONCLUSTERED", "TRAN", "DATABASE", "NOT", "TRANSACTION", "DBCC",
                                                    "NULL", "TRIGGER", "DEALLOCATE", "NULLIF", "TRUNCATE", "DECLARE",
                                                    "OF", "TSEQUAL", "DEFAULT", "OFF", "UNION", "DELETE", "OFFSETS",
                                                    "UNIQUE", "DENY", "ON", "UNPIVOT", "DESC", "OPEN", "UPDATE", "DISK",
                                                    "OPENDATASOURCE", "UPDATETEXT", "DISTINCT", "OPENQUERY", "USE",
                                                    "DISTRIBUTED", "OPENROWSET", "USER", "DOUBLE", "OPENXML", "VALUES",
                                                    "DROP", "OPTION", "VARYING", "DUMP", "OR", "VIEW", "ELSE", "ORDER",
                                                    "WAITFOR", "END", "OUTER", "WHEN", "ERRLVL", "OVER", "WHERE",
                                                    "ESCAPE", "PERCENT", "WHILE", "EXCEPT", "PIVOT", "WITH", "EXEC",
                                                    "PLAN", "WRITETEXT", "EXECUTE", "PRECISION",
                                                };

    }
}
